import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled } from '@ant-design/icons'
import { getGoodPro, deleteGoodPro, addGoodPro, editGoodPro } from "@net/good/product"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import "../../index.scss"
import Power from "@comm/power"
import { getGoodSourceInfo } from "@net/good/source"
import DialogTable from "../common/dialogTable"

interface IPorps { }
interface IStates {
    data: any[]
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    isEdit: boolean,
    page: number,
    pageSize: number,
    total: number,
    diaVisble: boolean,
    diaTabData: any[],
    sId:number,
    editItem:any,
}

export default class GoodProduct extends Component<IPorps, IStates> {
    // 表格设置
    private column = [
        {
            key: "name",
            dataIndex: "name",
            title: "名称",
            align: "center"
        },
        {
            key: "environment",
            dataIndex: "environment",
            title: "生产环境",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>不达标</Button>
                } else if (text === "1") {
                    return text = <Button type="link">达标</Button>
                }
            }
        },
        {
            key: "period",
            dataIndex: "period",
            title: "生产周期/月",
            align: "center"
        },
        {
            key: "amount",
            dataIndex: "amount",
            title: "生产数量/个",
            align: "center"
        },
        {
            key: "date",
            dataIndex: "date",
            title: "生产日期",
            align: "center"
        },
        {
            key: "qgp",
            dataIndex: "qgp",
            title: "保质期",
            align: "center"
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="good:product:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="good:product:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        }
    ]
    private columnDia = [
        {
            title: "名称",
            dataIndex: "name",
            key: "name",
            align: "center",
            fixed: "left"
        },
        {
            title: "采购",
            dataIndex: "purchase",
            key: "purchase",
            align: "center"
        },
        {
            title: "质量检测",
            dataIndex: "verify",
            key: "verify",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>审核驳回</Button>
                } else if (text === "1") {
                    return text = <Button type="link">待审核</Button>
                } else {
                    return text = <Button type="link" className="agree">审核通过</Button>
                }
            }
        },
        {
            title: "原料",
            dataIndex: "source",
            key: "source",
            align: "center"
        },
        {
            title: "仓储",
            dataIndex: "storage",
            key: "storage",
            align: "center"
        },
        {
            title: "供应商",
            dataIndex: "provider",
            key: "provider",
            align: "center"
        },
        {
            title: "创建时间",
            dataIndex: "screatetime",
            key: "screatetime",
            align: "center"
        },
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "食品名称",
                name: "name",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                    disabled:this.state.isEdit
                },
                style: { borderRadius: "5px" },
                id:"proName",
                onFocus: () => this.openDiaTable()
            },
            {
                type: 'select',
                label: "生产环境",
                name: "environment",
                option: [
                    { key: "0", value: "不达标" },
                    { key: "1", value: "达标" }
                ],
                rules: [
                    { required: true, message: "环境是否达标" }
                ],
                component: {
                    placeholder: "请输入环境是否达标",
                    disabled:this.state.editItem.environment === '1' ? true : false
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "生产周期",
                name: "period",
                rules: [
                    { required: true, message: "请输入生产周期" }
                ],
                component: {
                    placeholder: "请输入生产周期",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "生产数量",
                name: "amount",
                rules: [
                    { required: true, message: "请输入生产数量" }
                ],
                component: {
                    placeholder: "请输入生产数量",
                },
                style: { borderRadius: "5px" }
            },
            this.state.isEdit === false ?
                { type: "none" }
                :
                {
                    type: 'input',
                    label: "生产日期",
                    name: "date",
                    // rules: [
                    //     { required: true, message: "请输入生产日期" }
                    // ],
                    component: {
                        // placeholder: "请输入生产日期",
                        disabled: true,
                    },
                    style: { borderRadius: "5px" }
                },
                {
                    type: 'input',
                    label: "保质期",
                    name: "qgp",
                    rules: [
                        { required: true, message: "请输入保质期" }
                    ],
                    component: {
                        placeholder: "请输入保质期",
                    },
                    style: { borderRadius: "5px" }
                },
        ]
    }
    private searchCol = [
        {
            type: 'input',
            name:"fname",
            label:"食品名称",
            component: {
                placeholder: "请输入食品名称",
            },
            style: { borderRadius: "5px" }
        }
    ]
    private dialogFormRef = React.createRef<FormInstance>() as any
    constructor(props: IPorps) {
        super(props)
        this.state = {
            data: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            isEdit: false,
            total: 0,
            page: 1,
            pageSize: 5,
            diaVisble: false,
            diaTabData: [],
            sId:0,
            editItem:{},
        }
    }
    public componentDidMount() {
        this.fetchData(1, 5)
    }

    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        const res = await getGoodPro({ page, pageSize })
        res.data.data.map((item: any) => {
            return item.key = item.Id
        })
        this.setState({ loading: false, data: res.data.data, total: res.data.total })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    // 弹框表格页码切换监听事件
    public pageDiaChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            getGoodSourceInfo({ page, pageSize },null).then((res: any) => {
                res.data.data.forEach((item: any) => {
                    item.key = item.code
                })
                this.setState({ diaTabData: res.data.data, total: res.data.total })
            })
        }
    }
     // 打开选择货物弹框
     public openDiaTable = () => {
        this.setState({ diaVisble: true }, () => {
            this.pageDiaChange(1, 5)
        })
    }
    public diaSearch = async (name: string) => {
        let res:any
        name === "" ?
        res = await getGoodSourceInfo({ page: 1, pageSize: 5 },null)
        :
        res = await getGoodSourceInfo({ page: 1, pageSize: 1 }, {fname:name})
        const { status, msg, data,total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ diaTabData: data,total })
            }
    }
    public search = async (item:any) => {
        if (item.fname === undefined) {
            this.fetchData(this.state.page, this.state.pageSize)
            return
        }
        const res = await getGoodPro({ page: 1, pageSize: 5 }, item.fname)
        const { status, msg, data,total } = res.data
        if (status === 203) {
           message.error({content:msg,style:{marginTop:"20%"}})
        } else {
            message.success({content:msg,style:{marginTop:"20%"}})
            this.setState({ data: data,total })
        }
    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "食品生产添加", isEdit: false,editItem:{} })
    }
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "食品生产编辑", editId: item.Id, isEdit: true,editItem:item }, () => {
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id })
    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.sId = this.state.sId
        addGoodPro(values).then((res:any) => {
            const { msg, status } = res.data
            if (status === 203) {
               message.error({content:msg,style:{marginTop:"20%"}})
            } else if (status === 200) {
                message.success({content:msg,style:{marginTop:"20%"}})
                this.cancel()
                this.fetchData(this.state.page, this.state.pageSize)
            }
        })
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.editId
        values.sId = this.state.sId
        const res = await editGoodPro(values)
        const { status, msg } = res.data
        if (status === 203) {
           message.error({content:msg,style:{marginTop:"20%"}})
        } else if (status === 200) {
            message.success({content:msg,style:{marginTop:"20%"}})
            this.cancel()
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public delete = async () => {
        const res = await deleteGoodPro(this.state.delId)
        const { status, msg } = res.data
        if (status === 203) {
           message.error({content:msg,style:{marginTop:"20%"}})
        } else if (status === 200) {
            message.success({content:msg,style:{marginTop:"20%"}})
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false, isEdit: false })
        this.dialogFormRef.current.resetFields()
    }
    public selectRow = (item: any) => {
        if(item.verify === '0'){
            message.warn({content:'该食品原料审未通过',style:{marginTop:"20%"}})
            return
        }else if(item.verify === '1') {
            message.warn({content:'该食品原料未审核',style:{marginTop:"20%"}})
            return
        }
        this.dialogFormRef.current.setFieldsValue({ name: item.name})
        this.setState({ diaVisble: false,sId:item.Id })
    }
    public getDiaContent = () => {
        return (
            <DialogTable
                columns={this.columnDia}
                dataSource={this.state.diaTabData}
                pageChange={this.pageDiaChange}
                total={this.state.total}
                scroll={{ x: 1400 }}
                selectRow={this.selectRow}
                search={this.diaSearch}>
            </DialogTable>
        )
    }
    public renderDiaTab = () => {
        return (<Modal
            title="选择食品"
            visible={this.state.diaVisble}
            content={this.getDiaContent()}
            width="1200px"
            onCancel={() => { this.setState({ diaVisble: false }) }}
        />
        )
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    public renderModal = (item?: string) => {
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="good:product:save">
                    <Button type="primary" onClick={() => { this.openAddDialog() }}>新增生产</Button>
                </Power>
            </div>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="good:product:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        tableKey="goodProductTable"
                        pageChange={this.pageChange}
                        total={this.state.total}>
                    </InfoTable>
                </Card>
                {this.state.title === "食品生产添加" ? this.renderModal("") : this.renderModal()}
                {this.renderDiaTab()}
            </div>
        )
    }
}